<template>
<div class="cmt-box">
  <h3  class="title">发表评论</h3>
  <hr/>
  <textarea placeholder="请输入要BB的内容，限120字" maxlength="120" v-model="value"></textarea>
  <mt-button type="primary" size="large" @click="publish()">发表评论</mt-button>
  <div class="item" v-for="item in commentList" :key="item.id">
    <div class="subtitle">
      <img :src="item.img_url?item.img_url:touxiang" alt=""> 
      <div> 
        <span class="add-time">{{ item.username }}&nbsp;&nbsp;&nbsp;发表时间：{{item.add_time|initTime}}</span>
        <div class="content">{{ item.content }}</div>
      </div>
    </div>
  </div>

  <mt-button type="danger" size="large" plain @click="load()">加载更多。。。</mt-button>
</div>
</template>



<script>
import {Toast} from 'mint-ui'
import touxiang from '../img/touxiang.jpg'
export default {
  data(){
    return {
      commentList:[],
      page:0,
      value:"",
      touxiang:null
    }
  },
  async created(){
    this.load()
    
  },
  methods:{
    // 加载评论
    async load(){
      this.page++
      let data = await this.ajax.get(`/api/comment/${this.$props.prent_id}/${this.page}`)
      console.log(`/api/comment/${this.$props.prent_id}/${this.page}`)
      this.commentList=this.commentList.concat(data.data)
    },

    // 发表评论
    async publish(){
      let username=this.user.username
      let add_time= (new Date()).getTime()
      let data = await this.ajax.post({
        url:`/api/comment/${this.$props.prent_id}`,
        data:{
          value:this.value,
          username,
          add_time,
          img_url:this.user.headportrait_url
        }
      })
      if(data.err==0){
        let obj={
          username:username,
          add_time:add_time,
          content:this.value,
          img_url:this.user.headportrait_url
        }
        this.commentList.unshift(obj)
        this.value=""
      }else{
        Toast("评论失败请登录")
      }
    }
  },
  props:['prent_id'],
  computed:{
    user(){
      return this.$store.state.user.user
    }
  },
  created(){
    this.touxiang=touxiang
  }
}
</script>


<style lang="less" scoped>
.cmt-box{
  .title{
    padding-bottom: 10px;
  }
  textarea{
    padding: 5px;
    margin: 20px 0 0 0;
    height: 150px;
  }
  .item{
    font-size: 12px;
    // padding: 5px 0;
    .subtitle{
      padding: 5px 5px;
      margin-top:5px;
      white-space: nowrap;
      display: flex;
      img{
        width: 30px;
        height: 30px;
        vertical-align: top;
        border-radius: 50%;
      }
      .add-time{
        padding-left: 10px;
        color: #555;
        font-size: 10px;
      }
    }
    .content{
      padding: 5px;
      padding-left: 5px;
    }
  }
}
</style>